// pages/distribution/ma.js
const Controller = require('../controllers/controllers.js').controller;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    msg:'',
    info:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    Controller.appinfo({key:"key-user-share-title"}).then(res=>{
      this.setData({
        ['info.title']:res.data.baseData.content
      })
    })

    Controller.appinfo({key:"key-user-share-imgUrl"}).then(res=>{
      this.setData({
        ['info.imgUrl']:res.data.baseData.content
      })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  
   // 长按保存功能--授权部分
   saveToPhoto(e) {
    var that = this
    wx.showActionSheet({
      itemList: ['保存到相册'],
      success(res) {
        let url = that.data.customerImage;
        wx.getSetting({
          success: (res) => {
            if (!res.authSetting['scope.writePhotosAlbum']) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success: () => {
                  // 同意授权
                  that.saveImgInner(url);
                },
                fail: (res) => {
                  console.log(res);
                  wx.showModal({
                    title: '保存失败',
                    content: '请开启访问手机相册权限',
                    success(res) {
                      wx.openSetting()
                    }
                  })
                }
              })
            } else {
              // 已经授权了
              that.saveImgInner(url);
            }
          },
          fail: (res) => {
            console.log(res);
          }
        })
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  // 长按保存功能--保存部分
  saveImgInner(url) {
    wx.getImageInfo({
      src: url,
      success: (res) => {
        let path = res.path;
        wx.saveImageToPhotosAlbum({
          filePath: path,
          success: (res) => {
            console.log(res);
            wx.showToast({
              title: '已保存到相册',
            })
          },
          fail: (res) => {
            console.log(res);
          }
        })
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      this.makeShare()
  },
  makeShare(){
      Controller.makeShare().then(res=>{
        if(res.data.baseData){
          this.setData({
            msg:res.data.baseData
          })
        }
      })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {


      return{
        title:this.data.info.title,
        imageUrl:this.data.info.imgUrl
      }
  }
  
})